<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <!-- 添加角色 -->
      <el-button type="primary" @click="addRole">添加角色</el-button>
      <!-- 表格 -->
      <el-table
        :data="rolesList"
        border
        style="width: 100%">
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row class="myRow" v-for="(item1, index1) in scope.row.children" :key="item1.id"
            :class="['borderBottom', (index1===0)? 'borderTop': '']">
              <el-col :span="5">
                <el-tag @close="delRoleRightsById(scope.row, item1)" closable>{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="19">
                <el-row class="myRow" v-for="(item2, index2) in item1.children" :key="item2.id"
                :class="(index2!==0)? 'borderTop': ''">
                  <el-col :span="7">
                    <el-tag @close="delRoleRightsById(scope.row, item2)" closable type="success">{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="17">
                      <el-tag @close="delRoleRightsById(scope.row, item3)" closable type="warning"  v-for="(item3, index3) in item2.children" :key="item3.id"
                              :class="(index3!==0)? 'borderTop': ''">{{item3.authName}}
                      </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="roleName" label="角色名称" width="180"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述" width="180"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-tooltip effect="dark" content="修改" placement="top" :enterable="false">
              <el-button type="primary" icon="el-icon-edit" size="mini" @click="editBtn(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip effect="dark" content="删除" placement="top" :enterable="false">
              <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteBtn(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip effect="dark" content="权限管理" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" size="mini" @click="rgihtsBtn(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 修改角色对话框 -->
      <el-dialog
        title="修改角色"
        :visible.sync="editDialogVisible"
        width="50%"
        @close="resetEditDiolog"
      >
        <!-- 表单 -->
        <el-form :model="editForm" :rules="editFormrules" ref="editFormRef" label-width="100px">
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="editForm.roleName" clearable></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="editForm.roleDesc" clearable></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
    <el-button @click="editDialogVisibles">取 消</el-button>
    <el-button type="primary" @click="confirmEditDiolog">确 定</el-button>
  </span>
      </el-dialog>
      <!-- 权限管理对话框 -->
      <el-dialog
      title="权限管理"
      :visible.sync="rightsDialog"
      width="50%"
      @close="resetRightsDialog">
        <!-- 树节点-->
        <el-tree show-checkbox default-expand-all
                 :data="treeData" :props="treeProps"
                 node-key="id"
                 :default-checked-keys="defKeys"
                 ref="treeRef"></el-tree>
        <span slot="footer" class="dialog-footer">
          <el-button @click="cancelRightsDialog">取 消</el-button>
          <el-button type="primary" @click="submitRightsDialog">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 添加角色对话框 -->
      <el-dialog
        title="添加角色"
        :visible.sync="dialogAddRole"
        width="50%"
        @close="resetDiolog"
      >
        <!-- 表单 -->
        <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="addForm.roleName" clearable></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="addForm.roleDesc" type="password" clearable></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisibles">取 消</el-button>
    <el-button type="primary" @click="confirmDiolog">确 定</el-button>
  </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'Roles',
  data() {
    return {
      editFormrules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 2, max: 7, message: '角色名称2~7位', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 3, max: 10, message: '角色描述3~10位', trigger: 'blur' }
        ]
      },
      rolesList: [],
      editDialogVisible: false,
      editForm: {
        roleName: '',
        roleDesc: ''
      },
      editId: '',
      // 权限管理Diolog
      rightsDialog: false,
      treeData: [],
      treeProps: {
        children: 'children',
        label: 'authName'
      },
      defKeys: [],
      // 当前分配角色Id
      roleId: '',
      // 添加角色对话框
      dialogAddRole: false,
      addForm: {
        roleName: '',
        roleDesc: ''
      },
      addFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { max: '8', message: '角色名称太长', trigger: 'blur' }
        ],
        roleDesc: [
          { max: '10', message: '角色描述太长', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 角色列表
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error('获取信息失败，请刷新重试')
      this.rolesList = res.data
      console.log(this.rolesList)
    },
    // 关闭对话框
    resetEditDiolog() {
      this.$refs.editFormRef.resetFields()
    },
    // 添加角色按钮
    addRole() {
      this.dialogAddRole = true
    },
    // 添加角色
    async confirmDiolog() {
      const { data: res } = await this.$http.post('roles', this.addForm)
      if (res.meta.status !== 201) {
        return this.$message.error('添加失败')
      }
      this.$message.success('添加成功')
      this.dialogAddRole = false
      this.getRolesList()
    },
    // 关闭对话框(清空表单)
    resetDiolog() {
      this.$refs.addFormRef.resetFields()
    },
    // 对话框取消按钮
    dialogVisibles() {
      this.dialogAddRole = false
    },
    // 修改按钮
    editBtn(scope) {
      console.log(scope)
      this.editForm.roleName = scope.roleName
      this.editForm.roleDesc = scope.roleDesc
      this.editId = scope.id
      this.editDialogVisible = !this.editDialogVisible
    },
    // 确定按钮，修改用户
    confirmEditDiolog() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return this.$message.error('请确认修改信息')
        const { data: res } = await this.$http.put(`roles/${this.editId}`, this.editForm)
        if (res.meta.status !== 200) return this.$message.error('修改失败')
        this.$message.success('修改成功')
        this.editDialogVisible = false
        this.getRolesList()
      })
    },
    // 权限管理按钮
    async rgihtsBtn(scope) {
      // 获取所有权限数据
      this.roleId = scope.id
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) return this.$message.error('获取数据失败，请刷新重试')
      console.log(res)
      this.treeData = res.data
      // 分割
      this.recursionId(scope, this.defKeys)
      this.rightsDialog = true
      // console.log(scope)
      console.log(this.defKeys)
    },
    // 递归获得3级权限Id，存入defKeys数组中
    recursionId(data, arr) {
      if (!data.children) {
        return arr.push(data.id)
      }
      data.children.forEach(item =>
        this.recursionId(item, arr))
    },
    // 关闭权限管理Dialog
    resetRightsDialog() {
      // this.$refs.editFormRef.resetFields()
      this.defKeys = []
    },
    // 提交权限管理Dialog
    async submitRightsDialog() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      console.log(keys)
      const idStr = keys.join(',')
      console.log(idStr)
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: idStr })
      if (res.meta.status !== 200) return this.$message.error('分配权限失败，请刷新重试')
      this.$message.success('分配权限成功')
      this.getRolesList()
      this.rightsDialog = false
    },
    // 权限管理Dialog取消按钮
    cancelRightsDialog() {
      this.rightsDialog = false
    },
    // 修改对话框取消按钮
    editDialogVisibles() {
      this.editDialogVisible = false
    },
    // 删除用户按钮
    deleteBtn(scope) {
      this.$confirm('是否删除用户', '删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$message({
          type: 'success',
          message: '删除成功',
          showClose: 'true'
        })
        this.$http.delete(`roles/${scope.id}`)
        this.getRolesList()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消退出',
          showClose: 'true'
        })
      })
    },
    // 通过Id删除角色权限
    delRoleRightsById(role, rights) {
      this.$confirm('是否删除该权限？', '删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rights.id}}`)
        if (res.meta.status !== 200) {
          this.$message.error('删除失败')
        } else {
          this.$message.success('删除成功')
          role.children = res.data
        }
        // this.getRolesList()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消退出',
          showClose: 'true'
        })
      })
    },
    // Tree
    handleNodeClick(data) {
      console.log(data)
    }
  },
  created () {
    this.getRolesList()
  }
}
</script>

<style lang="less" scoped>
.el-tag{
  margin: 10px;
}
.myRow{
  display: flex;
  align-items: center;
}
.borderTop{
  border-top: 1px solid #eee;
}
.borderBottom{
  border-bottom: 1px solid #eee;
}
</style>
